<script lang="ts" setup>
import type { FormInst } from 'naive-ui';
import { NSpace, useMessage } from 'naive-ui';
import { ref } from 'vue';
import type { Fn } from '@vueuse/core';
import * as service from '@/views/im/user/modules/api';
import { isSuccess } from '@/utils/response';

const props = defineProps<{
  callback?: Fn;
}>();

const message = useMessage();
const formInstRef = ref<FormInst | null>(null);
const dataForm = ref<any>({});
const showModal = ref(false);
const rules = {
  cuid: {
    required: true
  },
  phone: {
    required: true
  },
  password: {
    required: true
  },
  nickName: {
    required: true
  }
};

function open() {
  showModal.value = true;
}

function close() {
  dataForm.value = {};
  showModal.value = false;
}

async function submit() {
  formInstRef.value?.validate((errors: any) => {
    if (!errors) {
      service.create(dataForm.value).then(response => {
        if (isSuccess(response)) {
          message.info('创建成功');
          close();
          if (props.callback) {
            props.callback();
          }
        }
      });
    }
  });
}
</script>

<template>
  <NButton type="info" @click="open()">新增</NButton>
  <n-modal v-model:show="showModal">
    <NSpace vertical>
      <n-card title="新增" class="card">
        <n-form ref="formInstRef" :label-width="80" :model="dataForm" :rules="rules" label-placement="left">
          <n-form-item label="ID:" path="cuid">
            <n-input v-model:value="dataForm.cuid" type="text"></n-input>
          </n-form-item>
          <n-form-item label="手机号:" path="phone">
            <n-input v-model:value="dataForm.phone" type="text"></n-input>
          </n-form-item>
          <n-form-item label="密码:" path="password">
            <n-input v-model:value="dataForm.password" type="password"></n-input>
          </n-form-item>
          <n-form-item label="昵称:" path="nickName">
            <n-input v-model:value="dataForm.nickName" type="text"></n-input>
          </n-form-item>
          <n-flex justify="end">
            <n-button @click="close()">取消</n-button>
            <n-button type="primary" @click="submit()">确定</n-button>
          </n-flex>
        </n-form>
      </n-card>
    </NSpace>
  </n-modal>
</template>

<style scoped>
.card {
  width: 350px;
}
</style>
@/service/api/chat-user
